﻿using AutoMapper;
using DFGK_WMS.Context;
using DFGK_WMS.IRepository;
using DFGK_WMS.Model.DTO;
using DFGK_WMS.Model.Models;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DFGK_WMS.Repository
{
    public class TMaterialCategoryRepository : BaseRepository<TMaterialCategory>, ITMaterialCategoryRepository
    {
        public TMaterialCategoryRepository(DFGK_DB context, IMapper mapper) : base(context, mapper)
        {
        }

        /// <summary>
        /// 添加物料分类
        /// </summary>
        /// <param name="m"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public bool AddTMaterialCategory(TMaterialCategory m)
        {
            var obj = Context.TMaterialCategories.AsNoTracking().FirstOrDefault(x => x.Code == m.Code);
            if (obj != null)
            {
                return false;
            }
            m.CreateUserId = m.NowUserId;
            m.CreateUserName = m.NowUserRealName;
            m.UpdateUserId = m.NowUserId;
            m.UpdateUserName = m.NowUserRealName;
            m.CreateDate = DateTime.Now;
            m.UpdateDate = DateTime.Now;
            Context.Add(m);
            return Context.SaveChanges() > 0;
        }

        /// <summary>
        /// 列表显示（弃用）
        /// </summary>
        /// <param name="mname"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="totalCount"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public List<MenuDto> GetMaterialCategortList(string mname, int pageIndex, int pageSize, out int totalCount)
        {
            var mlist = Context.TMaterialCategories.AsQueryable();
            if (!string.IsNullOrEmpty(mname))
            {
                mlist = mlist.Where(x => x.Name.Contains(mname));
            }

            if(mlist.Any())
            {
                mlist = mlist.OrderBy(x => x.ParentId);
                var mmlist = mlist.FirstOrDefault();
                var list2 = GetMenuLists(mlist.ToList(), mmlist.ParentId.GetValueOrDefault());
                totalCount = list2.Count();
                list2 = list2.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
                return list2;
            }
            
            var list = GetMenuLists(mlist.ToList(), 0);
            totalCount = list.Count();
            list = list.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
            return list;
        }

        /// <summary>
        /// 递归显示分类列表
        /// </summary>
        /// <param name="list"></param>
        /// <param name="pid"></param>
        /// <returns></returns>
        public static List<MenuDto> GetMenuLists(List<TMaterialCategory> list, int pid)
        {
            try
            {
                return list.Where(x => x.ParentId == pid).Select(x => new MenuDto
                {
                    id = x.Id,
                    ParentId = x.ParentId,
                    CreateUserName = x.CreateUserName,
                    UpdateUserName = x.UpdateUserName,
                    UpdateDate = x.UpdateDate,
                    Meta = new MetaDto
                    {
                        MenuName = x.Name,
                        MenuIcon=x.Code,
                    },
                    DisplayOrder = x.DisplayOrder,
                    children = GetMenuLists(list, x.Id)
                }).OrderBy(x => x.DisplayOrder).ToList();
            }
            catch (Exception)
            {

                throw;
            }
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="mid"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public bool DelTMaterialCategory(int mid)
        {
            var obj = Context.TMaterialCategories.Find(mid);
            if(obj!=null)
            {
                Context.TMaterialCategories.Remove(obj);
            }
            return Context.SaveChanges() > 0;
        }

        /// <summary>
        /// 查看
        /// </summary>
        /// <param name="mid"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public TMaterialCategory GetTMaterialCategoryById(int mid)
        {
            return Context.TMaterialCategories.Find(mid);
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="m"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public bool UpdTMaterialCategory(TMaterialCategory m)
        {
            var list = Context.TMaterialCategories.AsNoTracking().FirstOrDefault(x => x.Id != m.Id && x.Code == m.Code);

            if (list != null)
            {
                return false;
            }
            m.UpdateUserId = m.NowUserId;
            m.UpdateUserName = m.NowUserRealName;
            m.UpdateDate = DateTime.Now;
            Context.TMaterialCategories.Update(m);
            return Context.SaveChanges() > 0;
        }

        /// <summary>
        /// 添加-树形显示
        /// </summary>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public List<Menuitem> GetMaterialCateMenuitemList()
        {
            var list = Context.TMaterialCategories.AsNoTracking().AsQueryable();

            return GetMaterialCateMenuitemList(list.ToList(), 0);
        }

        public static List<Menuitem> GetMaterialCateMenuitemList(List<TMaterialCategory> list,int? pid)
        {
            return list.Where(x => x.ParentId == pid).Select(x=> new Menuitem
            {
                value=x.Id,
                label=x.Name,
                children= GetMaterialCateMenuitemList(list,x.Id).Count>0? GetMaterialCateMenuitemList(list,x.Id):null
            }).ToList();
        }

        public List<MenuDto> GetParentMaterialCategortList(string mname, int? parent, int pageIndex, int pageSize, out int totalCount)
        {
            var mlist = Context.TMaterialCategories.AsQueryable();
            if (!string.IsNullOrEmpty(mname))
            {
                mlist = mlist.Where(x => x.Name.Contains(mname));
            }
            if(parent!=null && parent>0)
            {
                mlist = mlist.Where(x => x.ParentId==parent);
            }
            if (mlist.Any())
            {
                mlist = mlist.OrderBy(x => x.ParentId);
                var mmlist = mlist.FirstOrDefault();
                var list2 = GetMenuLists(mlist.ToList(), mmlist.ParentId.GetValueOrDefault());
                totalCount = list2.Count();
                list2 = list2.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
                return list2;
            }

            var list = GetMenuLists(mlist.ToList(), 0);
            totalCount = list.Count();
            list = list.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
            return list;
        }

        /// <summary>
        /// 装备目录显示
        /// </summary>
        /// <param name="mname"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public List<TMaterialCategory> GetMaterialCategoryList(string EquipmentType, string name, string code, int pageIndex, int pageSize,out int totalCount)
        {
            var mlist = Context.TMaterialCategories.AsQueryable();

            if(EquipmentType != null)
            {
                mlist = mlist.Where(x => x.EquipmentType.Contains(EquipmentType));
            }
            if(name != null)
            {
                mlist = mlist.Where(x => x.Name.Contains(name));
            }
            if (code != null)
            {
                mlist = mlist.Where(x => x.Code.Contains(code));
            }

            totalCount = mlist.Count();

            return mlist.OrderByDescending(x => x.CreateDate).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
        }


        public bool UpdateMaterialCategory(List<TMaterialCategory> m)
        {
            Context.TMaterialCategories.AddRange(m);
            return Context.SaveChanges() > 0;
        }

        public List<TMaterialCategoryDto> GetMaterialByType(string? categoryName)
        {
            List<TMaterialCategoryDto> materialCategoryDtos = new List<TMaterialCategoryDto>();
            var materilList = Context.TMaterialCategories.AsQueryable();
            if(categoryName != null)
            {
                materilList = materilList.Where(x => x.Name.Contains(categoryName));
            }

            HashSet<string> existingTypes = new HashSet<string>();

            foreach (var item in materilList)
            {
                if (!existingTypes.Contains(item.EquipmentType))
                {
                    materialCategoryDtos.Add(new TMaterialCategoryDto
                    {
                        Name = item.EquipmentType,
                    });

                    existingTypes.Add(item.EquipmentType);
                }
            }
            foreach (var item in materialCategoryDtos)
            {
                var materialCategoryList = Context.TMaterialCategories.Where(x => x.EquipmentType == item.Name).ToList();
                List<TMaterialCategory> materialCategories = new List<TMaterialCategory>();
                materialCategories.AddRange(materialCategoryList);
                item.child = materialCategories;
            }

            return materialCategoryDtos.ToList();
            

        }
    }
}
